#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <assert.h>

/* 测试 */
#include "libmemcached/memcached.h"

int main(int argc, char *argv[])
{
    memcached_st *memc;
    memcached_return_t rc;

    printf("libmemcached version : %s\n",memcached_lib_version());

    memc = memcached_create(NULL);
    assert(memc);
#if 0
    memcached_server_list_st *servers;
    servers = memcached_server_list_append(NULL,"127.0.0.1",11211,&rc);
    assert(servers);

    rc = memcached_server_push(memc,servers);
    memcached_server_list_free(servers);
#else
    rc = memcached_server_add(memc,"localhost",0);
    assert(rc == MEMCACHED_SUCCESS);
#endif
    
    /* set key-value */
    char key[32] = "username";
    char *value;
    size_t value_length = 1024;

    value = (char*)malloc(value_length);
    assert(value);
    strcpy(value,"Bruce Lee");
    rc = memcached_set(memc,key,strlen(key),value,strlen(value),(time_t)9,(uint32_t)1001);
    if(rc!=MEMCACHED_SUCCESS)
	printf("set fail:%s\n",memcached_strerror(memc,rc));
    assert(rc == MEMCACHED_SUCCESS);

    strcpy(key,"code");
    strcpy(value,"123456");
    rc = memcached_set(memc,key,strlen(key),value,strlen(value),(time_t)9,(uint32_t)2001);
    assert(rc == MEMCACHED_SUCCESS);

    strcpy(key,"alias");
    strcpy(value,"水海云");
    rc = memcached_set(memc,key,strlen(key),value,strlen(value),(time_t)3,(uint32_t)3001);
    assert(rc == MEMCACHED_SUCCESS);

    free(value);
    
    /* fetch key-value */
    char *keys[] = {"username","code","alias"};
    size_t key_length[] = {8,4,5};
    uint32_t flags;
    char return_key[MEMCACHED_MAX_KEY]={0};
    size_t return_key_length;
    char *return_value;
    size_t return_value_length;

    //sleep(5);
    rc = memcached_mget(memc, keys, key_length, 3);
    assert(rc==MEMCACHED_SUCCESS);

    while ((return_value= memcached_fetch(memc, return_key, &return_key_length,
		    &return_value_length, &flags, &rc)))
    {
	printf("key:%s(%d B),value:%s(%d B),flags:%d\n",return_key,return_key_length,return_value,return_value_length,flags);
	free(return_value);
	memset(return_key,0,sizeof(return_key));
    }

    memcached_free(memc);
    exit(EXIT_SUCCESS);
}

